<?php

namespace app\common\model\xilujob;

use app\admin\model\User;
use app\common\library\Auth;
use app\common\library\xilujob\Geohash;
use think\db\Query;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;

class CompanyProfile extends Model
{

    use SoftDelete;

    const ENTERPRISE_AUDIT_STATUS_NONE = 0; //未审核
    const ENTERPRISE_AUDIT_STATUS_PASSED = 1; //已审核
    const ENTERPRISE_AUDIT_STATUS_WAITING = 2; //待审核
    const ENTERPRISE_AUDIT_STATUS_FAILED = 3; //未过审

    // 表名
    protected $name = 'xilujob_company_profile';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'personal_audit_status_text',
        'audit_status_text'
    ];
    public static function init() {
        self::afterInsert(function ($row){
            try {
                CompanyStatistics::create(['company_id' => $row->id,'user_id'=>$row->user_id]);
            }catch (\Exception $e) {

            }
        });
    }

    
    public function getPersonalAuditStatusList()
    {
        return ['1' => __('Personal_audit_status 1'), '2' => __('Personal_audit_status 2'), '3' => __('Personal_audit_status 3')];
    }

    public function getAuditStatusList()
    {
        return ['1' => __('Audit_status 1'), '2' => __('Audit_status 2'), '3' => __('Audit_status 3')];
    }


    public function getPersonalAuditStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['personal_audit_status']) ? $data['personal_audit_status'] : '');
        $list = $this->getPersonalAuditStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getAuditStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['audit_status']) ? $data['audit_status'] : '');
        $list = $this->getAuditStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function user() {
        return $this->belongsTo(\app\common\model\User::class,'user_id','id');
    }
    public function benefits() {
        return $this->belongsToMany('Benefit',EnterpriseBenefit::class,'benefit_id','enterprise_id');
    }

    public function enterpriseinfo() {
        return $this->hasOne('EnterpriseInfo', 'company_id')->setEagerlyType(0);
    }

    public function statistics() {
        return $this->hasOne('CompanyStatistics', 'company_id')->setEagerlyType(0);
    }

    /**
     * 搜索企业
     * @param $params
     */
    public static function searchCompanies($params) {
        $query = new self();
        $query->where('audit_status', 1);
        //城市筛选
        if($cityId = array_get($params, 'city_id')) {
            $query->where('city_id', $cityId);
        }
        //区域筛选
        if($district_id = array_get($params,'district_id')) {
            $query->where('district_id', $district_id);
        }
        //距离
        $distance = intval(array_get($params, 'distance', 0));//公里
        if($distance) {
            $pos = explode(',', array_get($params,'pos',''));
            $lng = array_get($pos,0);
            $lat = array_get($pos, 1);
            if($lng&&$lat) {
                //米
                if($distance) {
                    //限定数据为20公里附近的， 因最远的distance为10公里
                    $geohash = (new Geohash())->encode($lat, $lng,2);
                    $query->where('company_profile.id', 'in', function(Query $subQuery) use ($lat, $lng, $geohash, $distance, $cityId) {
                        $subQuery->name('xilujob_job_location')->alias('l')
                            ->field("l.id")
                            ->where('geohash','like', "$geohash%")
                            ->whereRaw("ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) < ".$distance*1000);
                        if($cityId) {
                            $subQuery->where('city_id', $cityId);
                        }
                    });
                }
            }
        }
        //分类
        if($categoryId = array_get($params, 'category_id')) {
            $query->where('industry_category_id', $categoryId);
        }
        if($scaleId = array_get($params, 'scale_id')) {
            $query->where('company_scale_id', $scaleId);
        }

        if($q = array_get($params,'q')) {
            $query->where('enterpriseinfo.address', 'like', "%$q%");
        }
        //排除黑名单企业
        $auth = Auth::instance();
        if($auth->isLogin()){
            $user = $auth->getUser();
            if($user->id) {
                $query->where('company_profile.id','not in', function($query) use($user){
                    $query->name('xilujob_user_blacklist_company')->where('user_id', $user->id)->field('company_id');
                });
            }
        }

        $query->with([
            'benefits'=>function(Query $query){$query->withField('id,name');},
            'enterpriseinfo'=>function(Query $query){$query->withField('id,company_name,full_name,city_id,company_scale_id,industry_category_id,logo');},
            'statistics' => function(Query $query){$query->withField('id,job_count,interview_comment_count');},
        ]);
        $query->join('XilujobArea area','enterpriseinfo.city_id=area.id','LEFT');
        $query->join('XilujobIndustryCategory category', 'enterpriseinfo.industry_category_id=category.id', 'LEFT');
        $query->join('XilujobCompanyScale scale', 'enterpriseinfo.company_scale_id=scale.id', 'LEFT');
        $query->field('area.shortname as city_name, category.name as industry_category_name, scale.name as company_scale_name');

        switch (array_get($params,'sort')) {
            case 1:
                //职位数量
                $query->order('statistics.job_count', 'desc');
                break;
            case 2:
                //面试评价数
                $query->order('statistics.interview_comment_count', 'desc');
                break;
            default:
                $query->order('top','desc');
                $query->order('statistics.job_count', 'desc');
        }

        $pagesize = array_get($params, 'pagesize', 10);
        if($pagesize<1) {
            $pagesize = 10;
        }
        $paginator = $query->paginate([
            'query' => $params, 'list_rows'=>$pagesize
        ]);
        return $paginator;
    }

}
